package com.sc.mockweipo.service;

import com.rabbitmq.client.AMQP;
import com.sc.mockweipo.config.LogRabbitConfig;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitManagementTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author sc
 * Created on  2017/12/22
 */
@Service
public class LikeService {


    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private AmqpAdmin amqpAdmin;
    @Autowired
    private RabbitManagementTemplate rabbitManagementTemplate;
    public void addBeauty(String name) {
        try {
            FanoutExchange fanoutExchange = new FanoutExchange(name);
            amqpAdmin.declareExchange(fanoutExchange);
            System.out.println("初始化交换器成功 :"+name);
            rabbitTemplate.convertAndSend(LogRabbitConfig.LOG_EXCHANGE,LogRabbitConfig.ROUTING_KEY,"初始化交换器"+name);

        }catch (Exception e){
            System.out.println("初始化交换器失败 :"+name);
        }
    }

    public void like(String boyName, String girlName) {

        Queue queue = new Queue(boyName);
        FanoutExchange fanoutExchange = (FanoutExchange) rabbitManagementTemplate.getExchange(girlName);
        amqpAdmin.declareQueue(queue);
        amqpAdmin.declareBinding(BindingBuilder.bind(queue).to(fanoutExchange));
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setQueueNames(boyName);
        container.setConnectionFactory(rabbitTemplate.getConnectionFactory());
        container.setMessageListener(new BoyListener());
        container.start();
        System.out.println(boyName+"关注了"+girlName);
    }

    public void postMessage(String girlName, String message) {
        System.out.println(girlName+"发了一条微博"+message);
        rabbitTemplate.convertAndSend(girlName,"",message);
    }

    public void unlike(String boyName, String girlName) {
            Queue queue = rabbitManagementTemplate.getQueue(boyName);
            rabbitManagementTemplate.deleteQueue(queue);
        rabbitTemplate.convertAndSend(LogRabbitConfig.LOG_EXCHANGE,LogRabbitConfig.ROUTING_KEY,boyName+"取关了"+girlName);
    }
}